package com.woniuxy.controller;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.woniuxy.config.DynamicDatasourceConfig;
import com.woniuxy.entity.HospitalMeta;
import com.woniuxy.service.IHospitalService;
import com.woniuxy.util.InitDBUtil;
import com.woniuxy.util.PageParam;
import com.woniuxy.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author：xurice
 * @date：Created in 2024/4/22 18:47
 * @description：saas医院
 */
@RestController
@RequestMapping("hospital")
public class HospitalController {
    @Autowired
    private IHospitalService hospitalService;


    @Autowired
    private DynamicDatasourceConfig dynamicDatasourceConfig;

    @Autowired
    private DynamicRoutingDataSource dataSource;

    @DS("master")
    @GetMapping("queryHospitalMetas")
    public ResponseData<?> queryHospitalMetas() {
        List<Map<String,String>> result = new ArrayList<>();
        for (String string : dataSource.getDataSources().keySet()) {
            Map<String,String> hospitalMeta = new HashMap<>();
            String hospitalName = dynamicDatasourceConfig.getHospitalBySchema(string);
            hospitalMeta.put("mysqlSchema",string);
            hospitalMeta.put("hospitalName",hospitalName);
            result.add(hospitalMeta);
        }
        return new ResponseData<>().ok(result);
    }

    @GetMapping("changeDB/{db}")
    public ResponseData<?> changeDB(@PathVariable("db") String db, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        HttpSession session = httpServletRequest.getSession();
        session.removeAttribute("db");
        session.setAttribute("db",db);
        return new ResponseData<>().ok(db);
    }

    @PostMapping("addHospital")
    public ResponseData<?> addHospital(@RequestBody HospitalMeta hospitalMeta){
        return hospitalService.addHospital(hospitalMeta);
    }

    @PostMapping("queryHospital")
    public ResponseData<?> queryHospital(@RequestBody PageParam<HospitalMeta> pageParam){
        return hospitalService.queryHospital(pageParam);
    }

    @PostMapping("addDB")
    public ResponseData<?> addDB(@RequestBody HospitalMeta hospitalMeta){
        return hospitalService.addDB(hospitalMeta);
    }
}
